package com.ebupt.migu.music.common.util;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.Charset;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import com.ebupt.migu.music.common.util.excelSheet.ExcelBuilder;

import lombok.extern.slf4j.Slf4j;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.io.outputstream.ZipOutputStream;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.model.enums.CompressionLevel;
import net.lingala.zip4j.model.enums.CompressionMethod;

/**
 * excel导出压缩方法
 *
 * @Author zhuar
 */
@Slf4j
public class ExcelExportAction {
    /**
     * 导出excel
     *
     * @param response
     * @param request
     * @param excel 封装的excel对象
     */
    public void exportExcel(HttpServletResponse response, HttpServletRequest request, ExcelUtils excel) {
        Workbook book;
        String fileName;
        String version = excel.getVersion();
        if (null == version || "".equals(version) || "2003".equals(version)) {
            book = new HSSFWorkbook();
            fileName = excel.getName() + ".xls";
        } else {
            book = new SXSSFWorkbook();
            fileName = excel.getName() + ".xlsx";
        }
        // 将数据填充到book
        ExcelBuilder.build(book, excel);
        String tempDir = System.getProperty("java.io.tmpdir");
        // String tempDir = "D:\\dir\\";
        File excelFile = new File(tempDir + File.separator + fileName);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(excelFile);
            book.write(fos);
            try {
                zipExport(response, request, excelFile, excel.getName());
            } catch (ZipException e) {
                log.error("add message err", e);
            }
        } catch (IOException e) {
            log.error("add message err", e);
        } finally {
            try {
                if (fos != null) {
                    fos.flush();
                    fos.close();
                }
            } catch (IOException e) {
                log.error("add message err", e);
            }
            if (excelFile.exists()) {
                excelFile.delete();
            }
        }
    }

    /**
     * 对book进行压缩导出
     *
     * @param response
     * @param request
     * @throws UnsupportedEncodingException
     * @throws ZipException
     */
    public void zipExport(HttpServletResponse response, HttpServletRequest request, File excelFile, String fileName)
            throws UnsupportedEncodingException, ZipException {
        OutputStream myout = null;
        ZipOutputStream zip = null;
        try {
            // 判断浏览器版本，进行对应的转码
            if (isIE(request)) {// IE
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else {//
                fileName = new String(fileName.getBytes("UTF-8"));
            }
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName + ".zip");
            try {
                zip = new ZipOutputStream(response.getOutputStream(), Charset.forName("GB2312"));
                ZipParameters parameters = new ZipParameters();
                // 压缩方式
                parameters.setCompressionMethod(CompressionMethod.DEFLATE);
                parameters.setCompressionLevel(CompressionLevel.NORMAL);
                // 加密方式
                if (excelFile != null && excelFile.exists()) {
                    zip.putNextEntry(parameters);
                    FileInputStream inputStream = new FileInputStream(excelFile);
                    byte[] readBuff = new byte[4096];
                    int readLen = -1;
                    while ((readLen = inputStream.read(readBuff)) != -1) {
                        zip.write(readBuff, 0, readLen);
                    }
                    inputStream.close();
                    zip.closeEntry();
                }
                zip.flush();
                zip.close();
                myout.flush();
                myout.close();
                if (response.isCommitted()) {
                    log.debug("请求信息已返回页面");
                } else {
                    log.debug("请求信息还没返回页面");
                }
            } catch (IOException e) {
                log.error("add message err", e);
            }

        } finally {
            try {
                zip.flush();
                zip.close();

                myout.flush();
                myout.close();
            } catch (Exception e) {
                log.error("add message err", e);
            }
        }
    }

    /**
     * 判断浏览器类型是否是IE,是则返回true,不是返回false
     *
     * @param request
     * @return
     */

    protected boolean isIE(HttpServletRequest request) {
        String userAgent = request.getHeader("USER-AGENT").toLowerCase();
        return userAgent.indexOf("msie") > 0 || userAgent.indexOf("trident") > 0;
    }
}